using Unity.PolySpatial.InputDevices;
using UnityEngine.InputSystem.EnhancedTouch;
using Touch = UnityEngine.InputSystem.EnhancedTouch.Touch;
using TouchPhase = UnityEngine.InputSystem.TouchPhase;

namespace Framework.Spatial
{
    public class SpatialInputManager : Singleton<SpatialInputManager>
    {
        private ISpatialInteractive _selectedInteractive;

        private void OnEnable()
        {
            EnhancedTouchSupport.Enable();
        }

        private void Update()
        {
            var activeTouches = Touch.activeTouches;

            if (activeTouches.Count > 0)
            {
                var primaryTouchData = EnhancedSpatialPointerSupport.GetPointerState(activeTouches[0]);
                var touchPhase = activeTouches[0].phase;

                // ReSharper disable once Unity.PerformanceCriticalCodeNullComparison
                if (primaryTouchData.targetObject != null)
                {
                    if (primaryTouchData.targetObject.TryGetComponent(out ISpatialInteractive spatialObject))
                    {
                        _selectedInteractive = spatialObject;
                        switch (touchPhase)
                        {
                            case TouchPhase.Began:
                                _selectedInteractive.OnTouchBegan();
                                break;
                            case TouchPhase.Moved:
                                _selectedInteractive.OnTouchMoved(primaryTouchData.deltaInteractionPosition);
                                break;
                            case TouchPhase.Ended:
                                _selectedInteractive.OnTouchEnded();
                                break;
                            case TouchPhase.Canceled:
                                _selectedInteractive.OnTouchCanceled();
                                break;
                        }
                    }
                }
            }
        }
    }
}